#!/usr/bin/env python
#coding=utf-8
# filename: handle.py

import web
import json
import time
import random
from configcenter import configCenter
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class winbulletgift(object):
    def GET(self):
        try:
            web.header("Access-Control-Allow-Origin", "*")
            web.header('content-type','text/json')
            cc = configCenter()
            config = cc.getConfig()
            host = config.get("global", "ip")
            port = config.get("global", "port")
            user = config.get("global", "user")
            pw = config.get("global", "password")
            database = config.get("global", "database")
            db = web.database(dbn='mysql', host=host, port=int(port), user=user, pw=pw, db=database, charset='utf8')
            prizes = db.select('prize')
            fp = prizes[0]
            begintime = fp.begintime
            print " -_- 1. begintime= ", begintime
            datadict = {}
            winners = []
            if begintime == "":
                print " -_- 2.Game does not start yet."
                datadict['winners'] = winners
                datadict['result'] = 'false'
                datadict['msg'] = '游戏还未开始'
            else:
                before = int(time.mktime(time.strptime(begintime,'%Y-%m-%d %H:%M:%S')))
                now = int(time.time())
                gifts = db.select('bulletgift', where="remaining > 0", order="importance desc")
                print "-_- 3. now = ", now
                print "-_- 4. before = ", before
                if(len(gifts) == 0):
                    print " -_- 5. Game is done."
                    datadict['winners'] = winners
                    datadict['result'] = 'false'
                    datadict['msg'] = '游戏已经束'
                else:
                    giftCandidates = []
                    for gift in gifts:
                        giftCandidates.append(gift)
                    if((now - before)/60 > 10):
                        print " -_- 6. Game in 10 mins. genreate new winners"
                        nowtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                        print " -_- 7. nowtime= ", nowtime
                        #bullets = db.query("select distinct mobile from party.bullet where mobile is not null and mobile <> '' and uptime between '" + begintime + "' and '" + nowtime + "'")
                        bullets = db.query("select mobile from sign ts where exists(select * from bullet tb where tb.mobile = ts.mobile and tb.mobile is not null and tb.mobile <> '' and tb.uptime between '" + begintime + "' and '" + nowtime + "')")
                        mobilelist = []
                        for bullet in bullets:
                            mobilelist.append(bullet.mobile)
                        mobilelist = list(set(mobilelist))
                        self.generateWiners(mobilelist,giftCandidates,nowtime,db)
                        db.update('prize', where="id=1", begintime=nowtime)
                    print " -_- 8. Game return the all winners"
                    gifthis = db.query('select * from bulletgifthis order by winat desc')
                    print " -_- 9. Game return the all winners: ", len(gifthis)
                    for winner in gifthis:
                        winners.append(winner.winner+" - "+str(winner.giftname))
                    #print winners
                    datadict = {}
                    datadict['winners'] = winners
                    datadict['result'] = 'true'
            return json.dumps(datadict, ensure_ascii=False)
        except Exception as e:
            return e.args

    def generateWiners(self, mobilelist, giftCandidates, nowtime, db):
        max = 20
        actualNums = len(mobilelist)
        crtwinners = []
        print "-_- 7.1 actualNums = ", actualNums
        for i in range(0, actualNums):
            print "-_- 7.2 i = ", i
            if(len(giftCandidates)<=0):
                print "-_- 7.3 i = gift all sell out.", i
                break
            if not mobilelist[i]:
                print "-_- 7.4 i, invalid mobile num: ", i, mobilelist[i]
                continue
            preWinGifts = db.select('bulletgifthis', where="winner = '"+ mobilelist[i] +"'")
            preGifts = []
            for pgift in preWinGifts:
                preGifts.append(pgift)
            if(len(preGifts) >= 2):
                print "-_- 7.5 i, this mobile num already won twice. ", i, mobilelist[i]
                continue
            gift=self.randomGift(1,giftCandidates,preGifts)
            if not gift:
                print "-_- 7.6 i, cannot generate any gift for this mobile after try 10 times. ", i, mobilelist[i]
                continue
            print "-_- 7.6 win a bullet git ", mobilelist[i], gift.name.encode("utf-8")
            db.insert('bulletgifthis',winner=mobilelist[i],giftname=gift.name,winat=nowtime, qty=1)
            crtwinners.append(str(mobilelist[i])+" - "+str(gift.name))
            gift.remaining = gift.remaining - 1
            db.update('bulletgift', where="id="+ str(gift.id), remaining=gift.remaining)
            if len(crtwinners) >= max:
                break
        return crtwinners

    def randomGift(self,times, giftCandidates, preGifts):
        print "-_- 7.2.1 random generate gift"
        if len(giftCandidates)<=0:
           print "-_- 7.2.2 no gift now"
           return ""
        index = random.randint(0,len(giftCandidates)-1)
        #print "-_- 7.2.1.2 random generate gift index ", index
        #print "-_- 7.2.1.3 gitCandidates len ", len(giftCandidates)
        #print "-_- 7.2.1.4 preGifts len ", len(preGifts)
        #print "-_- 7.2.1.5 random generate gift ", giftCandidates[index].id
        #print "-_- 7.2.1.6 random generate gift ", giftCandidates[index].name.encode("utf-8")
        if(giftCandidates[index].remaining <= 0):
           print "-_- 7.2.3 this gift remainig is 0 : ", giftCandidates[index].name.encode("utf-8")
           del giftCandidates[index]
           return self.randomGift(times, giftCandidates, preGifts)
        if len(preGifts) < 1:
           print "-_- 7.2.4 first time get bullet gift return , ", giftCandidates[index].name.encode("utf-8")
           return giftCandidates[index]
        if giftCandidates[index].name.encode("utf-8") != preGifts[0].giftname.encode("utf-8"):
           print "-_- 7.2.5 second time get different bullet gift return , ", giftCandidates[index].name.encode("utf-8")
           return giftCandidates[index]
        if times > 10:
           print "-_- 7.2.6 10 times get same bullet gift return empty "
           return ""
        print "-_- 7.2.7 try next time for this guy."
        return self.randomGift(times+1, giftCandidates, preGifts)
